<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">


      <!-- 使用 flex 布局，将 el-dropdown 和 el-button 自动排列到合适的位置 -->

      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width: 10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item v-for="(item, index) in tableTitle" :key="index" :command="item.label" v-if="item.tableProp !== 'outside'">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <p style="color: rgb(80,80,80);">是否已分配</p>
      <el-dropdown @command="handleType">
        <el-button type="primary" style="width: 10vw;">
          {{Type}}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item command="是">是</el-dropdown-item>
          <el-dropdown-item command="否">否</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button @click="handleSearch" :disabled="search ? false:true">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="addnew">新建</el-button>
    </el-header>

    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item, index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label"  :formatter="formatFlag" :width="item.width"></el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <!--    从这里开始是对话框内容-->
    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :rules="rules" :model="form" @submit.native.prevent>
        <el-form-item prop="landlordId" label="车主" :label-width="formLabelWidth">
          <el-select v-model="form.landlordId" placeholder="请选择车主" :disabled="!isEditable">
            <el-option
                v-for="item in landlords"
                :key="item.id"
                :label="item.name + ' ' + item.phone"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="number" label="车牌号码" :label-width="formLabelWidth">
          <el-input v-model="form.number" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>

        <div v-if="isCreateMode === false">
          <el-form-item prop="outside" label="是否在小区外" :label-width="formLabelWidth">
            <el-select v-model="form.outside" placeholder="请选择" :disabled="!isEditable">
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="landlordName" label="车主姓名" :label-width="formLabelWidth">
            <el-input v-model="form.landlordName" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item prop="landlordPhone" label="电话号码" :label-width="formLabelWidth">
            <el-input v-model="form.landlordPhone" autocomplete="off" readonly></el-input>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="isCreateMode === false">
          <el-button type="warning" @click="toggleEdit">编 辑</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-if="isCreateMode">
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--对话框内容结束-->

    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>

<script>
import http from '@/utils/http';
import { checkToken } from '@/router/index';

export default {
  data() {
    return {
      loading:false,
      filteredList:[],
      Type: '全部',
      Filter:'全部',
      search :"",
      currentPage: 1,
      pageSize: 10,
      allInfo:[],
      tableTitle:[
        {tableProp:"id",label:"车辆id"},
        {tableProp:"landlordId",label:"车主id"},
        {tableProp:"name",label:"车主姓名"},
        {tableProp:"number",label:"车牌号码"},
        {tableProp:"phone",label:"电话号码"},
        {tableProp:"outside",label:"是否在小区外"},

      ],
      tableData: [],

      // 从这里开始是对话框内容
      dialogFormVisible: false,
      form: {
        id: '', //车辆id
        landlordId: '',//车主id
        number: '', //车牌号码
        outside: '', //是否在小区外
        landlordName: '',//车主姓名
        landlordPhone: '',//电话号码
      },
      landlords: [], //后端返回的车主信息，包括：车主id、姓名、电话
      checked: true,
      rules: {
        number: [
          { required: true, message: '车牌不能为空', trigger: 'blur' },
          // { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[0-9]{5}(?![I])[A-Z0-9]$/, message: '请输入有效的车牌号码', trigger: 'blur' }
        ],
        outside: [
          { required: true, message: '该选项不能为空', trigger: 'blur' }
        ],
        // landlordId: [
        //   { required: true, message: '车主id不能为空', trigger: 'blur' },
        //   // { min: 1, max: 10, message: '业主id最多10位', trigger: 'blur' }
        // ],
      },
      originalForm: null, // 保存原始数据副本
      isEditable: false, // 控制输入框是否可编辑
      isCreateMode: false,
      dialogTitle: '', // 对话框标题
      formLabelWidth: '120px' // 标签宽度
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted(){
    this.getAllData();
  },
  methods: {
    handleType(command){
      this.Type = command;
      this.handleSearch();
    },
    handleRefresh(){
      this.getAllData();
    },
    formatFlag(row, column, cellValue) {
      // row: 当前行数据对象
      // column: 当前列的配置对象
      // cellValue: 当前单元格的值，即 row[column.property]

      if (column.property === 'outside') {
        return cellValue === 1 ? '是' : '否';
      }

      // 如果不是 flag 列，可以根据需要返回其他的格式化结果
      return cellValue;
    },
    getAllData(){
      this.loading=true;
      http.get("/admin/car/getAllCar")
          .then((response) => {
            console.log("request succeed!");
            const Result = response.data;
            this.allInfo = Result.data;
            this.tableData = this.allInfo;
            this.loading=false;

            this.loading = true;
            // 获取landlords列表
            http.get("/admin/car/getLandlordVos")
                .then(response => {
                  // 请求成功，处理响应数据
                  // console.log(response);
                  const Result = response.data;
                  this.landlords = Result.data;
                  this.landlords.unshift({id: 0, name: '无', phone: ''});
                  this.loading = false;
                })
                .catch(function (error) {

                });
          }).catch((error) => {
        console.log("request error !");
        console.error(error);
      });
    },
    handleReset(){
      this.search = "";
      this.Filter = "全部";
      this.tableData = this.allInfo;

    },
    handleFilter(command) {
      this.Filter = command;
    },
    handleSearch() {
      if (this.search) {
        if (this.Filter === "全部") {
          this.tableData = this.allInfo.filter(item => {
            return Object.keys(item).some(key => {
              // 排除 key 为 'outside' 的项
              if (key === 'outside') {
                return false;
              }
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });
          });
        } else {
          const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
          this.tableData = this.allInfo.filter(item => {
            const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
            return value.includes(this.search.toLowerCase());
          });
        }
      }
      // 然后进行类型过滤
      if (this.Type !== '全部') {
        let st = -1;
        switch (this.Type) {
          case '是':
            st = 1;
            break;
          case '否':
            st = 0;
            break;
        }
        this.tableData = this.tableData.filter(item => (item.landlordId != 0 && st != 0 || item.landlordId == 0 && st == 0));
      }
    },
    //删除按钮
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({

          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    deleteData(row){
      // 删除界面上的
      this.tableData = this.tableData.filter(item=>item!=row);
      // 更新总数据源
      this.allInfo = this.tableData;

      // 检查当前页是否大于删除后的数据页数，若是则重置为前一页
      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }
      // //删除数据库中
      http.get("/admin/car/deleteCar",{
        params:{
          id: row.id
        }
      }).then(response=>{
        console.log(response.data.data);
      })
    }
    ,
    handlePageChange(page) {
      this.currentPage = page;
    },

    // 从这里开始是对话框内容的函数
    //新建
    addnew() {
      // 需要重置表单数据
      setTimeout(()=>{
        this.resetForm();
      }, 100)

      this.dialogFormVisible = true;//显示对话框
      this.isEditable = true;//刚开始就能编辑
      this.isCreateMode = true; // 设置为新建模式
      this.dialogTitle = '新建车辆';
    },
    resetForm() {
      // 重置数据模型
      // 重置表单控件状态
      this.$nextTick(() => {
        this.form = {
          id: '', //车辆id
          landlordId: '',//车主id
          number: '', //车牌号码
          outside: '', //是否在小区外
          landlordName: '',//车主姓名
          landlordPhone: '',//电话号码
        };
        this.$refs.form.resetFields();
      });
    },
    //详情按钮
    handleDetails(row) {
      this.$nextTick(() => {
        this.resetForm();
        // 睡一觉，确保form的数据能够更新
        setTimeout(()=>{
          console.log("车辆信息", row);
          this.form.id = row.id;
          this.form.landlordId = row.landlordId;
          this.form.number = row.number;
          this.form.outside = (row.outside == '1' ? '是' : '否');
          this.form.landlordName = row.name;
          this.form.landlordPhone = row.phone;
          console.log('车辆car', this.form);

          this.originalForm = { ...this.form }; // 深拷贝数据以保存状态
          this.dialogFormVisible = true;//显示对话框
          this.isEditable = false;//刚开始不能编辑
          this.isCreateMode = false; // 设置为详情模式
          this.dialogTitle = '车辆详情|信息编辑';
        }, 100)
      });

      // this.form = { ...row }; // 将当前数据赋值给表单
      // console.log("test:", this.originalForm, this.form);

    },
    toggleEdit() {
      this.$message.warning("正在进行编辑");
      this.isEditable = true;
    },
    cancel() {
      // 恢复到编辑前的状态
      if (this.isCreateMode === false) {
        this.form = { ...this.originalForm };
      }
      this.dialogFormVisible = false;
      // 重置编辑状态
      this.isEditable = false;
    },
    // 确认修改
    confirm() {
      this.$refs.form.validate((valid) => {
        // console.log("originalForm1", this.originalForm);
        if (valid) {
          let payload = {
            id: this.form.id,
            landlordId: this.form.landlordId,
            outside: (this.form.outside === '是' ? '1' : '0')
          };
          if (this.form.number !== this.originalForm.number) {
            payload.number = this.form.number;
          }
          http.post('/admin/car/updateCar', payload)
              .then(response => {
                const Result = response.data;
                if (Result.success) {
                  this.getAllData();
                  this.$message.success("修改成功！")
                  this.dialogFormVisible = false; //关闭对话框
                  this.isEditable = false; // 重置编辑状态
                  console.log('Success:', response.data);
                } else {
                  this.$message.error(Result.errorMsg);
                  console.log('Error:', response.data);
                }
              })
              .catch(error => {
                this.$message.error("请求失败！")
                console.error('Error:', error);
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          // 恢复到编辑前的状态
          // console.log("originalForm2", this.originalForm);
          this.form = { ...this.originalForm };
          console.log(this.form);
          // return false;
        }
      });
    },
    //确认添加
    confirmAdd() {
      this.$refs.form.validate((valid) => {
        // console.log(this.form);
        if (valid) {
          http.get("/admin/car/addCar", {
            params: {
              number: this.form.number,
              landlordId: this.form.landlordId,
            }
          })
              .then(response => {
                // 请求成功，处理响应数据
                console.log(response);
                const Result = response.data;
                if (Result.success) {
                  // 添加成功
                  this.getAllData();
                  this.$message.success("添加成功！")
                  this.dialogFormVisible = false; //关闭对话框
                  this.isEditable = false; // 重置编辑状态
                } else {
                  // 添加失败
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(function (error) {
                // 请求失败，处理错误情况
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          // 恢复编辑前的状态
          // this.form = { ...this.originalForm };
          return false;
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
/* Add custom styling for your component */
</style>
